package com.cdtu.controller;

import com.cdtu.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@RestController
//解决跨域问题
@CrossOrigin
@RequestMapping("/study")
public class StudyFileController {
    @Value("${reggie.pathVideo}")
    private String basePath;
    @Value("${reggie.pathItem}")
    private String ItemPath;
    //    String Filename = UUID.randomUUID().toString();
    String Filename = "";
    @RequestMapping("/upload")
    public R<String> uploadVedio(MultipartFile file) {
        return uploadIO(file,basePath);
    }
    @RequestMapping("/ItemUpload")
    public R<String> uploadItem(MultipartFile file) {
        return uploadIO(file,ItemPath);
    }

    //文件删除(路径)
    public Boolean uploadCustomPathFile(String path){
        return FileSystemUtils.deleteRecursively(new File(path));
    }
    //文件删除(文件)
    public Boolean uploadCustomPathFile(File file){
        return FileSystemUtils.deleteRecursively(file);
    }

    public R<String> uploadIO(MultipartFile file,String PathIO){
        String originalFilename = file.getOriginalFilename();
        System.out.println("---originalFilename------------------"+originalFilename);
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//        Filename = Filename + suffix;
        Date date=new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Filename = format.format(date)+originalFilename;
        log.info("上传文件：{}", file);
        File file1 = new File(PathIO);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        try {
            file.transferTo(new File(PathIO + Filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(Filename);
    }

    @RequestMapping("/play")
    public void play(String name, HttpServletRequest request, HttpServletResponse response) {
        response.reset();
        String rangeInHeader = request.getHeader("Range");//形如bytes=xxx-xxx
        String range = null;
        String fileFullPath = basePath + name;
        File file = new File(fileFullPath);
        long fileLength = file.length();
//        if (fileLength==0){
//            response.setStatus(404);
//            return;
//        }
        long start;
        if ("".equals(rangeInHeader) || rangeInHeader == null)
            start = 0;
        else {
            range = rangeInHeader.split("=")[1].split("-")[0];//得到起始字节位置
            start = Long.valueOf(range);
            response.setStatus(206);
            String contentType = "video/mp4";
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + start + "-" + (fileLength - 1) + "/" + fileLength);
        }
        response.setContentLengthLong(fileLength);
        //System.out.println("起始字节位置：" + start);
        try (BufferedInputStream br = new BufferedInputStream(new FileInputStream(file))) {

            //---------跳过已传输过的字节--------------
            br.skip(start);
            OutputStream  out = response.getOutputStream();

            //-----------向输出流写入数据---------
            int len;
            byte[] buf = new byte[2];//根据实际情况修改大小
            while ((len = br.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("连接断开");
        }
    }
    @RequestMapping("/download")
    public void download(String filePath, HttpServletResponse response) throws IOException {
//        // 清空输出流
//        response.reset();
//        response.setContentType("application/x-download;charset=UTF-8");
//        response.setHeader("Content-Disposition", "attachment;filename="+ new String(filePath.getBytes("utf-8"), "utf-8"));
//        OutputStream os=response.getOutputStream();
//        //下载文件的路径
//        String downPath = basePath+filePath;
//        //读取目标文件
//        File f = new File(downPath);
//        //创建输入流
//        InputStream is = new FileInputStream(f);
//        //做一些业务判断，我这里简单点直接输出，你也可以封装到实体类返回具体信息
//        if (is == null) {
//            System.out.println("文件不存在");
//        }
////        利用IOUtils将输入流的内容 复制到输出流
////        org.apache.tomcat.util.http.fileupload.IOUtils
////        项目搭建是自动集成了这个类 直接使用即可
//        IOUtils.copy(is, os);
//        os.flush();
//        is.close();
//        os.close();
//        return null;
//        try {
//            //设置响应内容类型。
//            response.setContentType("video/mp4");
//            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
//            // 创建文件输入流，读取服务器的文件。
//            System.out.println("地址:"+basePath+filePath);
//            FileInputStream fileInputStream = new FileInputStream(new File(basePath + filePath));
//            // 获取文件输出流，以写数据到前端。
//            ServletOutputStream outputStream = response.getOutputStream();
//            IoUtil.copy(fileInputStream,outputStream);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        //        System.out.println("下载"+name);
        long stime = System.currentTimeMillis();
        try {
            File file=null;
            //设置响应内容类型。
            if (filePath.endsWith("mp4")){
                response.setContentType("video/mp4");
                file=new File(basePath+filePath);
            }else if (filePath.endsWith("xls")){
                response.setContentType("application/vnd.ms-excel");
                file=new File(ItemPath+filePath);
            }else if (filePath.endsWith("xlsx")){
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                file=new File(ItemPath+filePath);
            }
            // 创建文件输入流，读取服务器的文件。
            FileInputStream fileInputStream = new FileInputStream(file);
            BufferedInputStream bufferedInputStream=new BufferedInputStream(fileInputStream);
//            System.out.println("文件名"+name);
            int len = 0;
            byte[] bytes = new byte[5120];
            // 获取文件输出流，以写数据到前端。
            ServletOutputStream outputStream = response.getOutputStream();
            // 循环读取
            while ((len = bufferedInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                // 刷新
                outputStream.flush();
            }
            // 关闭资源
            fileInputStream.close();
            bufferedInputStream.close();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        long etime = System.currentTimeMillis();
        System.out.printf("执行时长：%d 秒.", (etime - stime));
    }
}
